package com.enqualcomm.kids.activities;


import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.enqualcomm.kids.BuildConfig;
import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.bean.StringMessage;
import com.enqualcomm.kids.component.DownloadAppIntentService;
import com.enqualcomm.kids.config.ImageUriFactory;
import com.enqualcomm.kids.config.StateCode;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.config.userdefault.UserDefault;
import com.enqualcomm.kids.config.userdefault.UserTerminalDefault;
import com.enqualcomm.kids.mvp.NetworkModel;
import com.enqualcomm.kids.network.HttpRequest;
import com.enqualcomm.kids.network.NetworkListener;
import com.enqualcomm.kids.network.SocketRequest;
import com.enqualcomm.kids.network.http.request.GetUserInfoParams;
import com.enqualcomm.kids.network.http.response.GetUserInfoResult;
import com.enqualcomm.kids.network.socket.request.GetNewAppParams;
import com.enqualcomm.kids.network.socket.request.UpdatePushNotificationParams;
import com.enqualcomm.kids.network.socket.response.BasicResult;
import com.enqualcomm.kids.network.socket.response.GetNewAppResult;
import com.enqualcomm.kids.network.socket.response.TerminallistResult;
import com.enqualcomm.kids.view.dialog.CommitDialogCallBack;
import com.enqualcomm.kids.view.dialog.MyPromptDialog;
import com.enqualcomm.kids.view.dialog.MyUpdateCommitDialog;
import com.facebook.drawee.view.SimpleDraweeView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.io.File;

import common.utils.MyLogger;
import common.utils.PromptUtil;
import de.greenrobot.event.EventBus;

@EActivity(R.layout.activity_app_setting)
public class AppSettingActivity extends BaseActivity {

    @ViewById(R.id.username_tv)
    TextView username_tv;
    @ViewById(R.id.about_rl)
    View about_rl;
    AppDefault appDefault;
    NetworkModel networkModel;

    @ViewById(R.id.user_nickname_tv)
    TextView user_nickname_tv;
    @ViewById(R.id.help_rl)
    RelativeLayout help_rl;

    @ViewById(R.id.user_header_iv)
    SimpleDraweeView user_header_iv;
    @ViewById(R.id.user_manu_line_v)
    View user_manu_line_v;
    @ViewById(R.id.bing_phone_rl)
    View bing_phone_rl;
    @ViewById(R.id.show_bind_phone_account_tv)
    TextView show_bind_phone_account_tv;
    @ViewById(R.id.show_no_bind_phone_account_tv)
    TextView show_no_bind_phone_account_tv;
    @ViewById(R.id.wx_gg_rl)
    View wx_gg_rl;

    private TerminallistResult.Terminal terminal;

    @AfterViews
    void setupViews() {
        findViewById(R.id.title_bar_left_iv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView title_bar_name = (TextView) findViewById(R.id.title_bar_title_tv);
        title_bar_name.setText(getString(R.string.system_settings));

        TextView title_bar_terminal_name_tv = (TextView) findViewById(R.id.title_bar_terminal_name_tv);
        View title_bar_terminal_icon_iv = findViewById(R.id.title_bar_terminal_icon_iv);
        title_bar_terminal_icon_iv.setVisibility(View.GONE);
        title_bar_terminal_name_tv.setVisibility(View.VISIBLE);
        title_bar_terminal_name_tv.setText(getString(R.string.system_settings));

        appDefault = new AppDefault();
        String username;
        if (!appDefault.getLoginByWX() || (appDefault.getLoginByWX() && appDefault.getWXLoginType() == 1)) {
            username = appDefault.getUsername();
        } else {
            UserDefault userDefault = new UserDefault(appDefault.getUserid());
            if (userDefault.getLoginOtherResult() != null && userDefault.getLoginOtherResult().result != null
                    && !TextUtils.isEmpty(userDefault.getLoginOtherResult().result.phone)) {
                username = userDefault.getLoginOtherResult().result.phone;
            } else if (userDefault.getLoginOtherResult() != null && userDefault.getLoginOtherResult().result != null
                    && !TextUtils.isEmpty(userDefault.getLoginOtherResult().result.phonea)) {
                username = userDefault.getLoginOtherResult().result.phonea;
            } else {
                username = appDefault.getWXUserNickName();
            }
//            username_tv.setVisibility(View.GONE);
        }

        if (appDefault.getLoginByWX()) {
            username_tv.setText(getString(R.string.set_wx_number) + " " + username);
        } else {
            username_tv.setText(getString(R.string.account_desc) + " " + username);
        }

        networkModel = new NetworkModel();
        terminal = getTerminal();

        //用户头像
        Uri uri = null;
        UserDefault userDefault = new UserDefault(appDefault.getUserid());
        String userHeader = userDefault.getHeader();
        if (appDefault.getLoginByWX()) {
            uri = Uri.parse(appDefault.getWXUserHeadUrl());
        } else {
            if (userHeader != null && !appDefault.getLoginByWX()) {//用户有按照最新的协议上传头像
                uri = ImageUriFactory.getUri(userHeader);
            } else {//老用户
                if (terminal != null) {
                    String header = new UserTerminalDefault(terminal.userterminalid).getHeader();
                    if (new File(header).exists()) {
                        uri = ImageUriFactory.getFileUri(header);
                    } else {
                        uri = ImageUriFactory.getAssetsUri(header);
                    }
                } else {
                    uri = ImageUriFactory.getAssetsUri("relationship_9.png");
                }
            }
        }

        user_header_iv.setImageURI(uri, this);

        GetUserInfoResult info = userDefault.getInfo();
        if (appDefault.getLoginByWX()) {
            user_nickname_tv.setText(appDefault.getWXUserNickName());
        } else {
            if (info != null && info.name != null) {
                user_nickname_tv.setText(info.name);
            }
        }

//        help_rl.setVisibility(View.GONE);
//        user_manu_line_v.setVisibility(View.GONE);
        if ("星王-爱星定位宝".equals(BuildConfig.CHANNEL) || "西瓜皮-西瓜皮".equals(BuildConfig.CHANNEL)
                || "前海毅德-儿童天使".equals(BuildConfig.CHANNEL) || "一米阳光-守护星plus".equals(BuildConfig.CHANNEL)
                || "喜书郎-喜书郎".equals(BuildConfig.CHANNEL)) {
            help_rl.setVisibility(View.GONE);
            user_manu_line_v.setVisibility(View.GONE);
        }
        getUserInfo();


        if (!appDefault.getLoginByWX()) {
            bing_phone_rl.setVisibility(View.GONE);
        } else {
            if (appDefault.getWXLoginType() == 1) {
                show_bind_phone_account_tv.setVisibility(View.VISIBLE);
                show_no_bind_phone_account_tv.setVisibility(View.GONE);
                show_no_bind_phone_account_tv.setClickable(false);
                show_bind_phone_account_tv.setClickable(true);
            } else {
                show_bind_phone_account_tv.setVisibility(View.GONE);
                show_no_bind_phone_account_tv.setVisibility(View.VISIBLE);
                show_no_bind_phone_account_tv.setClickable(true);
                show_bind_phone_account_tv.setClickable(false);
            }
        }

        if ("品冠达-平安星智能".equals(BuildConfig.CHANNEL)) {
            wx_gg_rl.setVisibility(View.GONE);
        }

    }

    private void getUserInfo() {
        networkModel.loadDataFromServer(new HttpRequest<GetUserInfoResult>(new GetUserInfoParams(appDefault.getUserid(), appDefault.getUserkey())
                , new NetworkListener<GetUserInfoResult>() {
            @Override
            public void onError(VolleyError error) {
            }

            @Override
            public void onSuccess(GetUserInfoResult response) {
                if (response.code == StateCode.OK) {//更新头像和名字
                    if (appDefault == null) {
                        appDefault = new AppDefault();
                    }
                    UserDefault userDefault = new UserDefault(appDefault.getUserid());
                    userDefault.setInfo(response);

                    if (!appDefault.getLoginByWX()) {
                        if (response.pictureid != null) {
                            Uri uri = ImageUriFactory.getUri(response.pictureid);
                            user_header_iv.setImageURI(uri, this);
                        }
                        if (response.name != null) {
                            user_nickname_tv.setText(response.name);
                        }
                    }

                }
            }
        }));
    }

    @Click(R.id.userinfo_rl)
    void userInfo() {
        EventBus eventBus = EventBus.getDefault();
        if (!eventBus.isRegistered(this)) {
            eventBus.register(this);
        }

        if (terminal != null) {
            startActivityWithTerminal(UserInfoActivity_.class, terminal);
        } else {
            startActivity(UserInfoActivity_.class);
        }
    }

    public void onEvent(StringMessage message) {
        MyLogger.kLog().i("修改手机号码============================");
        switch (message.msg) {
            case StringMessage.USER_INFO_UPDATED:
                if (appDefault.getLoginByWX()) {
                    MyLogger.kLog().i("修改手机号码============================2");
//                    String username = new UserDefault(terminal.terminalid).getLoginOtherResult().result.phone;
//                    username_tv.setText(getString(R.string.set_wx_number) + " " + username);
                    setupViews();
                } else {
                    getUserInfo();
                }

                break;
            case StringMessage.REFRESH_TERMINALLIST:
                MyLogger.kLog().i("绑定后有消息");
                EventBus.getDefault().post(StringMessage.REFRESH_TERMINALLIST);
                setupViews();
                finish();
                break;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        networkModel.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Click(R.id.offline_map_rl)
    void offlineMap() {
        startActivity(OfflineMapActivity.class);
    }

    @Click(R.id.notification_rl)
    void notifycationSetting() {
        startActivity(NotifycationSettingActivity.class);
    }

    @Click(R.id.unbind_phone_rl)
    void unBind() {
        EventBus.getDefault().post(StringMessage.REFRESH_TERMINALLIST);
        finish();
    }
//    @Click(R.id.scan_download_rl)
//    void scanDownload(){
//        startActivity(ShareAppActivity.class);
//    }

//    @Click(R.id.alter_password_rl)
//    void alterPassword(){
//        startActivityForResult(new Intent(this, AlterPasswordActivity.class), 100);
//    }


//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode==100&&resultCode==AlterPasswordActivity.PASSWORD_CHANGE){//修改密码，terminalid，userid都会变...
//            EventBus.getDefault().post(new StringMessage(StringMessage.REFRESH_TERMINALLIST));
//            finish();
//        }
//    }

//    @Click(R.id.check_update_rl)
//    void checkUpdate(){
//        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            showProgress();
//            networkModel.loadDataFromServer(new SocketRequest<GetNewAppResult>(new GetNewAppParams(1, String.valueOf(BuildConfig.VERSION_CODE), BuildConfig.CHANNEL),
//                    new NetworkListener<GetNewAppResult>() {
//                        @Override
//                        public void onError(VolleyError error) {
//                            hideProgress();
//                            PromptUtil.toast(getApplicationContext(), R.string.app_no_connection);
//                        }
//
//                        @Override
//                        public void onSuccess(GetNewAppResult response) {
//                            hideProgress();
//                            if (response.code == StateCode.OK){
//                                if (response.result.url!=null) {
//                                    showCommitDialog(response);
//                                }else {
//                                    PromptUtil.toast(getApplication(),"您已升级到最新版本");
//                                }
//                            }
//                        }
//                    }));
//        }else{
//            PromptUtil.toast(getApplicationContext(), R.string.check_sdcard);
//        }
//    }

    @Click(R.id.graphics_lock_rl)
    void setGestureLock() {
        startActivity(GestureLockControlActivity_.class);
    }

    @Click(R.id.about_rl)
    void about() {
        startActivity(AboutActivity.class);
//        startActivityWithTerminal(AboutActivity.class,terminal);
    }

    @Click(R.id.exit_account)
    void exit() {
        //要先注销推送服务
        UpdatePushNotificationParams params = new UpdatePushNotificationParams(appDefault.getUserkey(), appDefault.getUserid(), appDefault.getPushClientId(), 2);
        networkModel.loadDataFromServer(new SocketRequest<BasicResult>(params, null));
        finish();
        EventBus.getDefault().post(new StringMessage(StringMessage.EXIT));
    }


    private void showCommitDialog(final GetNewAppResult appInfo) {
        new MyUpdateCommitDialog(this, appInfo, new MyUpdateCommitDialog.UpdateCommitDialogCallBack() {

            @Override
            public void onCommit() {
                // 后台下载升级
                Intent service = new Intent(getApplicationContext(), DownloadAppIntentService.class);
                service.putExtra("url", appInfo.result.url);
                startService(service);
            }

            @Override
            public void onCancel() {
            }
        }).show();
    }

    @Click(R.id.help_rl)
    void help() {
//        startActivity(HelpActivity_.class);
        startActivityWithTerminal(HelpActivity_.class, terminal);
    }

    @Click(R.id.bing_phone_rl)
    void bindPhoneAccount() {
        if (appDefault.getWXLoginType() != 1) {
            showNoBindPhone();
        } else {
            showBindPhone();
        }
    }

    @Click(R.id.wx_gg_rl)
    void startWXGG() {
        startActivity(WXGGDisplayActivity_.class);
    }

    @Click(R.id.show_bind_phone_account_tv)
    void showBindPhone() {
        startActivityWithTerminal(ShowBindAccountActivity_.class, terminal);
    }

    @Click(R.id.show_no_bind_phone_account_tv)
    void showNoBindPhone() {
        UserDefault userDefault = new UserDefault(appDefault.getUserid());
        if (userDefault.getTerminals() != null && userDefault.getTerminals().size() > 0) {
            MyPromptDialog dialog = new MyPromptDialog(this, getString(R.string.choose_wx_bind_phone_title), getString(R.string.choose_wx_bind_phone_notice), new CommitDialogCallBack() {
                @Override
                public void onCommit() {

                }

                @Override
                public void onCancel() {

                }
            });
            dialog.show();
        } else {
            EventBus eventBus = EventBus.getDefault();
            if (!eventBus.isRegistered(this)) {
                eventBus.register(this);
            }
            startActivityWithTerminal(BindPhoneAccountActivity_.class, terminal);
        }
    }
}
